# encoding:utf-8
import os
import sys
import base64
import urllib,urllib.parse,urllib.request
import json

def img_reco(img_name,access_token):
    '''
    菜品识别
    '''
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish"
    path = os.path.abspath(os.path.dirname(sys.argv[0])).split("dish_recognition")[0]
    # 二进制方式打开图片文件
    f = open(path+'\\media\\img\\'+img_name, 'rb')
    img = base64.b64encode(f.read())
    params = {"image":img,"top_num":5}
    # params = urllib3.urlencode(params)
    params = urllib.parse.urlencode(params).encode(encoding='UTF8')

    request_url = request_url + "?access_token="+access_token
    # request = urllib2.Request(url=request_url, data=params)
    request = urllib.request.Request(request_url,params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    # response = urllib2.urlopen(request)
    response =  urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    # print(json.loads(content))
    if content:
        return json.loads(content)

if __name__ == '__main__':
    data=img_reco("4.jpg")
    print(data)